import modelExtend from 'dva-model-extend'
import { query, doReportBy, listLogs } from 'services/report'
import { getCurrentTenant } from 'services/app'
import { getGrantIdsBy } from 'services/reportConfig'
import FileSaver from 'file-saver'

import { request, config } from 'utils'

const { defaultPageSize } = config
const model = {
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  }
}
const lwjPageModel = modelExtend(model, {

  state: {
    items: [],
    pagination: {
      current: 1,
      total: 0,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      showQuickJumper: true,
      defaultPageSize: defaultPageSize
    }
  },

  reducers: {
    querySuccess(state, { payload }) {
      // console.log(`querySuccess payload: ${JSON.stringify(payload)}`); const
      // {items, pagination} = payload; console.log(`items payload:
      // ${JSON.stringify(items)}`); console.log(`pagination payload:
      // ${JSON.stringify(pagination)}`);
      return {
        ...state,
        items: payload.items,
        pagination: {
          ...state.pagination,
          current: payload.page,
          total: payload.totalCount
        }
      }
    }
  }
})

export default modelExtend(lwjPageModel, {
  namespace: 'report',
  state: {
    currentItem: {},
    modalConditionVisible: false,
    modalHistoryVisible: false,
    modalDetailVisible: false,
    modalMemoVisible: false,
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    currentTenant: ''
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/reports' || pathname === '/') {
          dispatch({ type: 'query', payload: {} })
          dispatch({ type: 'currentTenant', payload: {} })
        }
      })
    }
  },
  effects: {
    * query({
      payload
    }, { select, call, put }) {
      const pageOptions = yield select(({ report }) => report.pageOptions);
      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...payload
        }
      }
      const data = yield call(query, queryPayload);
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    * showExportLogs({
      payload
    }, { call, put }) {
      const { currentItem } = payload;
      const params = {
        reportId: currentItem.id
      };
      const data = yield call(listLogs, params);
      currentItem.listLogs = data;
      yield put({
        type: 'showModalHistory',
        payload: {
          currentItem: currentItem
        }
      });
    },
    * showDetail({
      payload
    }, { call, put }) {
      const { currentItem } = payload;
      const grantedIds = yield call(getGrantIdsBy, currentItem.id);
      currentItem.grantedIds = grantedIds;
      yield put({
        type: 'showModalDetail',
        payload: {
          currentItem: currentItem
        }
      });
    },
    * doExport({
      payload
    }, { call, put }) {
      const { currentItem, queryParams } = payload;
      const data = yield call(doReportBy, currentItem.id, queryParams);
      try {
        FileSaver.saveAs(data, `${currentItem.reportName}.xls`);
      } catch (e) {
        console.error(e);
      }
    },
    * currentTenant({
      payload
    }, { select, call, put }) {
      const data = yield call(getCurrentTenant);
      yield put({
        type: 'saveCurrentTenant',
        payload: {
          currentTenant: data.result.displayName,
        }
      })
    },
  },
  reducers: {
    showModalConditions(state, { payload }) {
      return {
        ...state,
        ...payload,
        modalConditionVisible: true
      }
    },
    showModalHistory(state, { payload }) {
      return {
        ...state,
        ...payload,
        modalHistoryVisible: true
      }
    },
    showModalDetail(state, { payload }) {
      return {
        ...state,
        ...payload,
        modalDetailVisible: true
      }
    },
    showModalMemo(state, { payload }) {
      return {
        ...state,
        ...payload,
        modalMemoVisible: true
      }
    },
    saveCurrentTenant(state, { payload }) {
      return {
        ...state,
        currentTenant: payload
      }
    },
    hideModal(state, { payload }) {
      return {
        ...state,
        modalConditionVisible: false,
        modalHistoryVisible: false,
        modalDetailVisible: false,
        modalMemoVisible: false
      }
    }
  }
})
